#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from cvisio import *

TV_ID=0
TV_X=1
TV_Y=2
TV_TYPE=3
TV_TEXT=4
TV_LINE=5

def get_conn_text(node1):
        try:
            t1 = "[%2d]"%node1[TV_ID]
        except:
            if isinstance(node1, int):
                t1 = "%2d"%node1
            elif node1 is None:
                t1 = "nil"
        return t1

class StringBuff:
    def __init__(self):
        self._list = []
        self.raw_handler = sys.stdout
        sys.stdout = self

    def write(self, line):
        self._list.append(line)
    
    def pop(self):
        sys.stdout = self.raw_handler
        return ''.join(self._list)

class puml_drawer:
    def __init__(self, filename, autoquit=0):
        self.end_list = []
        self.count = 0
        print("puml: "+filename)

    def print_prefix(self, n, x):
        print FUN_DELIM*x,

    def print_blank(self):
        print ''

    def draw_fun(self, name, exp, x, y, max_depth=100, dirpath=''):
        buf = StringBuff()
        print '```plantuml'
        print '@startuml'
        print u'title 函数%s流程图'%name
        print ' start'
        self.print_func_exp(exp, x, y)
        print ' stop'
        print '@enduml'
        print '```'
        ret = buf.pop()
        return ret

    def print_func_exp(self, exp, x=0, y=0, ext=None):
        ttype = exp[TK_TYPE]

        if (ttype[0:4] == 'DONE'):
            try:    # 打印alias
                node = exp[TK_EXPR][0]
                node_data = node
                comment = get_exp_head(node_data)

                idx = comment.index('@alias')
                text = comment[idx+7:].rstrip()
                if (text[-1] == '?'):
                    text2 = text[0:-1]
                # self.draw_node(NODE_P, x, y+count, text2, node[TK_START])
                self.print_prefix(node[TK_START], x)
                print ':@%s@;'%text2
                return 'DONENODE'
            except:
                pass

        if (
                ttype == 'DONENODE'
                or ttype == 'DONECODE'
                ):
            # 如果是最终节点，答应即可
            for node in (exp[TK_EXPR]):
                self.print_prefix(node[TK_START], x)
                print ':%s;'%node[TK_EXPR].strip()
        elif (
                ttype == 'DONEBREAK'
                or ttype == 'DONECONTINUE'
                or ttype == 'DONEGOTO'
                ):
            op = ttype[4:len(ttype)].lower()
            # 如果是最终节点，答应即可
            for node in (exp[TK_EXPR]):
                self.print_prefix(node[TK_START], x)
                print ':%s;'%node[TK_EXPR].strip()
            if ttype == 'DONEBREAK':
                self.print_prefix(node[TK_START], x)
                print 'break;'
            self.print_blank()
        elif (ttype == 'DOENRETURN'):
            op = ttype[4:len(ttype)].lower()
            # 如果是最终节点，答应即可
            for node in (exp[TK_EXPR]):
                self.print_prefix(node[TK_START], x)
                print ':%s;'%node[TK_EXPR].strip()
            print 'stop'
        elif (ttype == 'DONEIFELSE'):
            # 获取if的第一个节点
            node = exp[TK_EXPR][0]

            self.print_prefix(node[TK_START], x)
            print 'if (%s) then (Y)'%(node[TK_EXPR])

            # 获取IF函数的节点
            self.print_func_exp(exp[TK_EXPR][1], x+1, y+1)

            # 获取ELSE
            self.print_prefix(node[TK_MID], x)
            print 'else(N)'

            # 获取ELSE函数的节点
            self.print_func_exp(exp[TK_EXPR][2], x+1, y+1)

            self.print_prefix(node[TK_END], x)
            print 'endif'

            self.print_blank()
        elif (ttype == 'DONEIF'
                or ttype == 'DONEWHILE'
                ):
            op = ttype[4:len(ttype)].lower()
            # 获取 第一个节点
            node = exp[TK_EXPR][0]

            self.print_prefix(node[TK_START], x)
            print op+'(%s) then (Y)'%(node[TK_EXPR])

            # 获取函数的节点
            self.print_func_exp(exp[TK_EXPR][1], x+1, y+1)

            self.print_prefix(node[TK_END], x)
            print 'end%s'%(op)
            self.print_blank()
        elif (ttype == ttype == 'DONECASE'):
            # 获取 第一个节点
            node = exp[TK_EXPR][0]

            self.print_prefix(node[TK_START], x)
            print 'elseif (%s) then (%s)'%(ext or '', node[TK_EXPR])

            # 获取函数的节点
            self.print_func_exp(exp[TK_EXPR][1], x+1, y+1)
        elif (ttype == 'DONEDEFAULT'):
            # 获取 第一个节点
            node = exp[TK_EXPR][0]

            self.print_prefix(node[TK_START], x)
            print 'else (%s)'%(node[TK_EXPR])

            # 获取函数的节点
            self.print_func_exp(exp[TK_EXPR][1], x+1, y+1)

        elif (ttype == 'DONEDO'):
            op = ttype[4:len(ttype)].lower()
            # 获取if的第一个节点
            node = exp[TK_EXPR][0]
            self.print_prefix(node[TK_START], x)
            print 'repeat'

            # 获取函数的节点
            self.print_func_exp(exp[TK_EXPR][1], x+1, y+1)

            self.print_prefix(node[TK_END], x)
            print 'repeat while <(%s)'%(node[TK_EXPR])
            self.print_blank()
        elif (ttype == 'DONEFOR'):
            op = ttype[4:len(ttype)].lower()
            # 获取if的第一个节点
            node = exp[TK_EXPR][0]

            self.print_prefix(node[TK_START], x)
            print ':%s;'%(node[TK_EXPR0].strip())

            self.print_prefix(node[TK_START], x)
            print 'while (%s) is (Y)'%(node[TK_EXPR])

            # 获取函数的节点
            self.print_func_exp(exp[TK_EXPR][1], x+1, y+1)

            self.print_prefix(node[TK_END], x)
            print ':%s;'%(node[TK_EXPR2].strip())
            self.print_prefix(node[TK_END], x)
            print 'endwhile (N)'
            self.print_blank()
        elif (ttype == 'DONESWITCH'):
            op = ttype[4:len(ttype)].lower()
            # 获取 第一个节点
            node = exp[TK_EXPR][0]

            self.print_prefix(node[TK_START], x)
            print 'if (%s) then (SW)'%(node[TK_EXPR])

            # 获取函数的节点
            # self.print_func_exp(exp[TK_EXPR][1], x+1, y+1)
            j=0
            for node2 in (exp[TK_EXPR][1][TK_EXPR]):
                # 遍历switch里面的分支判断
                if (node2[TK_TYPE] == 'DONECASE'
                        or node2[TK_TYPE] == 'DONEDEFAULT'
                        ):
                    j+=1
                self.print_func_exp(node2, x+j, y+1, node[-1])
            self.print_prefix(node[TK_END], x)
            print 'endif '
            self.print_blank()
        elif (ttype == 'NODE'):
            # 说明需要解析
            for node in exp[TK_EXPR]:
                self.print_func_exp(node, x, y)
            
        return ttype